//导入数据库模块
const mysql = require('../db/index')
//导入bcryptjs模块
const bcryptjs = require('bcryptjs')
//导入config模块
const config = require('../config')
//导入jsonwebtoken模块用来生成token字符串
const jwt = require('jsonwebtoken')
//注册
exports.registered = (req, res) => {
    const userinfo = req.body
    if (!userinfo.ename || !userinfo.epass) {
        return res.cc('账号密码不能为空！')
    }
    const sql = 'select * from employee where ename = ?'
    mysql.query(sql, userinfo.ename, (err, result) => {
        if (err) return res.cc(err)
        if (result.length > 0) return res.cc('账号已存在，请更换后重试！')
        //加密操作
        userinfo.epass = bcryptjs.hashSync(userinfo.epass, 10)
        //账号可用
        const sql = 'insert into employee set ?'
        mysql.query(sql, [{ ename: userinfo.ename, epass: userinfo.epass, realname: userinfo.realname, esex: userinfo.esex, entrydate: userinfo.entrydate, position: userinfo.position, sal: userinfo.sal, estatus: userinfo.estatus }], (err, result) => {
            if (err) return res.cc(err)
            if (result.affectedRows != 1) return res.cc('注册员工失败，请重试！')
            res.cc('注册成功', 0)
        })
    })
}
//登录
exports.login = (req, res) => {
    const userinfo = req.body
    const sql = 'select * from employee where ename = ?'
    mysql.query(sql, userinfo.ename, (err, result) => {
        if (err) return res.cc(err)
        if (result.length != 1) return res.cc('账号不存在，请重试！')
        const compareResult = bcryptjs.compareSync(userinfo.epass, result[0].epass)
        if (!compareResult) return res.cc('登录失败，密码错误！')
        //可以登录
        //剔除密码
        const user = { ...result[0], epass: '' }
        //生成token字符串
        const tokneStr = jwt.sign(user, config.jwtSecretKey, { expiresIn: '10h' })
        res.send({ status: 0, message: '登录成功！', token: 'Bearer ' + tokneStr })
    })
}



